<?php

/**
 * Class Common_tools
 */
class Common_tools extends CI_Model
{
    /**
     * Common_tools constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    /** AJAX 返回 跟踪信息,直接返回了
     * @param string $message
     * @param bool $ok
     */
    public function _JSONRESULT($message = '错误信息', $ok = false)
    {
        $result = array();
        $result["success"] = $ok;
        $result["msg"] = print_r($message, true);
        $result["obj"] = "";
        echo json_encode($result);
        exit;
    }

    /** 调整目录路径
     * @param $path  路径
     * @return mixed|string 路径
     */
    public function dir_path($path)
    {
        $path = str_replace('\\', '/', $path);
        if (substr($path, -1) != '/') $path = $path . '/';
        return $path;
    }

    /**
     * 列出目录下的所有文件
     *
     * @param str $path 目录
     * @param str $exts 后缀
     * @param array $list 路径数组
     * @return array 返回路径数组
     */
    public function dir_list($path, $exts = '', $list = array())
    {
        $path = self::dir_path($path);
        $files = glob($path . '*');
        foreach ($files as $v) {
            if (!$exts || preg_match("/\.($exts)/i", $v)) {
                $list[] = $v;
                if (is_dir($v)) {
                    $list = dir_list($v, $exts, $list);
                }
            }
        }
        return $list;
    }


    /** EXCEL日期字段格式读取
     *
     * @param $date EXCEL日期
     * @return false|string PHP日期
     */
    public function _excelDateTophp($date)
    {
        $time = ($date - 25569) * 24 * 60 * 60;
        return date('Y-m-d', $time);
    }


    /** 添加默认数据字段
     * @param $record 需要添加默认字段的记录
     * @return mixed 已经添加默认字段的记录
     */
    public function _dbaddtion($record)
    {
        $record['IS_DISABLED'] = 0;
        $record['createdatetime'] = date("Y-m-d H:i:s");
        $record['createuser'] = $this->session->userdata['sessioninfo']['userId'];
        return $record;
    }

    /** 按照多个字段对二维数组排序
     *  sortArrByManyField($array1,'id',SORT_ASC,'name',SORT_ASC,'age',SORT_DESC);
     * @return mixed|null  排序结果数组
     * @throws Exception 格式错误
     */
    public function sortArrByManyField()
    {
        $args = func_get_args();
        if (empty($args)) {
            return null;
        }
        $arr = array_shift($args);
        if (!is_array($arr)) {
            throw new Exception("第一个参数不为数组");
        }
        foreach ($args as $key => $field) {
            if (is_string($field)) {
                $temp = array();
                foreach ($arr as $index => $val) {
                    $temp[$index] = $val[$field];
                }
                $args[$key] = $temp;
            }
        }
        $args[] = &$arr;//引用值
        call_user_func_array('array_multisort', $args);
        return array_pop($args);
    }

    /** 根据config二维数组配置，用config中newfield字段内容，替换config中oldfield字段内容
     *
     * @param $str 被替换的字符串
     * @param $config  搜索条件 key=>value
     * @param $oldfield  config二维数组中的判断字段
     * @param $newfield  config二维数组中的替换字段
     * @return string 返回结果字符串
     */
    public function arrayreplace($str, $config, $oldfield, $newfield)
    {
        $list = explode(',', $str);
        foreach ($config as $arr) {
            if (in_array($arr[$oldfield], $list))
                foreach ($list as $key => $value)
                    if ($value == $arr[$oldfield]) $list[$key] = $arr[$newfield];
        }
        $str = implode(',', $list);
        return $str;
    }

    /** 取得上传文件参数
     *
     * @param $name 上传文件$_FILES中提取对应文件
     * @return string 保存的文件路径名
     */
    public function getFile($name)
    {
        //获取上传的excel临时文件
        $path = $_FILES[$name]["tmp_name"];
        if (!file_exists($path)) {
            $result["success"] = false;
            $result["msg"] = "上传文件失败！";
            echo json_encode($result);
            exit;
        }
        //将临时文件移动当前目录，可自定义存储位置
        $info = pathinfo($_FILES[$name]["name"]);
        $dir = "./upload/" . Date("Ym") . "/";
        if (!file_exists($dir)) {
            mkdir($dir);
        }
        $tmp_path = "./upload/" . Date("Ym") . "/cfgfile_" . strtotime("now") . "." . $info['extension'];
        move_uploaded_file($path, $tmp_path);
        //将获取在服务器中的Excel文件，此处为上传文件名
        return $tmp_path;
    }

    /** 二维数组，根据keyfield，提取valuefield，到array
     *
     * @param $data
     * @param $keyfield
     * @param $valuefield
     * @return array
     */
    public function arr2ToList($data, $keyfield, $valuefield)
    {
        $result = array();
        foreach ($data as $item) {
            $result[$item[$keyfield]] = $item[$valuefield];
        }
        return $result;
    }

    public function chgPassword($username, $password)
    {
        $this->load->model("public/Common_centreon", "centreon");
        $this->centreon->chgPasswd($username, $password);
        $this->db->where('username', $username);
        $update = array();
        $update['password'] = $password;
        $update['lastchange'] = Date('Y-m-d H:i:s');
        $update['modifydatetime'] = Date('Y-m-d H:i:s');
        $update['modifyuser'] = $username;
        $this->db->update('sys_user', $update);
    }

    public function downloadFileRename($filename, $out_filename)
    {
        if (!file_exists($filename)) {
            echo '<script>alert("文件没有找到")</script>' . $filename;
            exit;
        } else {
            header('Accept-Ranges: bytes');
            header('Accept-Length: ' . filesize($filename));
            header('Content-Transfer-Encoding: binary');
            header('Content-type: application/octet-stream');
            header('Content-Disposition: attachment; filename=' . $out_filename);
            header('Content-Type: application/octet-stream; name=' . $out_filename);
            if (is_file($filename) && is_readable($filename)) {
                $file = fopen($filename, "r");
                echo fread($file, filesize($filename));
                fclose($file);
            }
            exit;
        }
    }
}
